/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TweetRay;

import java.util.ArrayList;



/**
 *
 *           __
 *          /  \
 *          ^  ^
 *         / \/ \
 *         | .| .|
 *         \_/\_/
 *          |  |
 *          \ o/
 *          /  \
 *         |    |
 *         | | ||
 *         | 0 0|
 *         |    |
 */
public class UTFReader {

    private  ArrayList <Integer> codepoints;


    int buffer = 0;
    int pointer = 0;




    public UTFReader(){
        codepoints = new ArrayList();
    }

    public UTFReader(ArrayList <Integer> codepoints){
        this.codepoints =codepoints;
    }
    

    public void addPoint(int point){
        codepoints.add(new Integer(point));
    }



    public int getBits(int numBits){

        int toRet = 0;

        if (pointer == 0){
            load14();
            toRet = buffer & ((int)Math.pow(2.d,(double)numBits)-1);
            pointer += numBits;
        }
        else if ((pointer + numBits) <= 14){
            toRet = buffer & (((int)Math.pow(2.d,(double)numBits)-1) << pointer);
            toRet = toRet >> pointer;
            pointer += numBits;
        }
        else{
            
            //construct the bottom
            int remain = 14-pointer;
            int upper = numBits-remain;
            int tmp = buffer >> pointer;
            
            load14();
            toRet = buffer & ((int)Math.pow(2.d,(double)upper)-1);
            toRet = toRet << remain;
            toRet |= tmp;
            pointer = upper;

        }
        //System.out.println("read:" + toRet);
        return toRet;
    }

    private void load14(){
            Integer tmp = codepoints.get(0);
            buffer = tmp.intValue();
            pointer = 0;
            codepoints.remove(0);
    }

}
